package edu.nf.takeoutdemo.commons.config;


import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDateTime;

/**
 *
 * @author zjl
 * @date 2025/10/19
 */
@Configuration
public class RedisConfig {
    /**
     * 自定义RedisTemplate,主要是自定义键值的序列化类型
     * @param redisConnectionFactory 注入连接工厂
     * @return
     */
//    @Bean
//    public RedisTemplate<String,?> redisTemplate(RedisConnectionFactory redisConnectionFactory){
//        // 创建RedisTemplate实例
//        RedisTemplate<String,?> redisTemplate = new RedisTemplate<>();
//        // 设置连接工厂
//        redisTemplate.setConnectionFactory(redisConnectionFactory);
//
//        // 自定义key的序列化器(使用StingRedisSerializer)
//        StringRedisSerializer keySerializer = new StringRedisSerializer();
//        redisTemplate.setKeySerializer(keySerializer);
//        redisTemplate.setHashKeySerializer(keySerializer);
//        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.registerModule(new JavaTimeModule());
//
//
//        // 自定义value的序列化器(使用GenericJackson2JsonRedisSerializer)
//        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
//        redisTemplate.setValueSerializer(valueSerializer);
//        redisTemplate.setHashValueSerializer(valueSerializer);
//
//        return redisTemplate;
//    }

    @Bean
    public RedisTemplate<String,?> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, ?> tpl = new RedisTemplate<>();
        tpl.setConnectionFactory(factory);

        // 1. 专门给 Redis 用的 ObjectMapper
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule());
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 关键：设置 LocalDateTime 的格式
        om.configOverride(LocalDateTime.class)
                .setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd HH:mm"));

        // 2. 统一 value 序列化器
        GenericJackson2JsonRedisSerializer valueSerializer =
                new GenericJackson2JsonRedisSerializer(om);

        // 3.  key 始终用 String
        StringRedisSerializer keySerializer = new StringRedisSerializer();

        tpl.setKeySerializer(keySerializer);
        tpl.setHashKeySerializer(keySerializer);
        tpl.setValueSerializer(valueSerializer);
        tpl.setHashValueSerializer(valueSerializer);
        return tpl;
    }
}
